/*************************************************************************
 * File Name:    Add_Binary.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013-11-6 13:56:14
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Add Binary
 |
 | Given two binary strings, return their sum (also a binary string).
 |
 | For example,
 | a = "11"
 | b = "1"
 | Return "100".
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

class Solution {
public:
    string addBinary(string a, string b)
    {
        int m = a.size();
        int n = b.size();
        
        if (m < n) {
            swap(m, n);
            swap(a, b);
        }
        for (int i = 0; i < m; ++i) a[i] -= '0';
        for (int i = 0; i < n; ++i) b[i] -= '0';
        
        int carry = 0;
        for (int i = n - 1; i >= 0; --i) {
            a[i + m - n] += b[i] + carry;
            carry = a[i + m - n] / 2;
            
            if (a[i + m - n] & 1) a[i + m - n] = '1';
            else a[i + m - n] = '0';
        }
        for (int i = m - n - 1; i >= 0; --i) {
            a[i] += carry;
            carry = a[i] / 2;
            if (a[i] & 1) a[i] = '1';
            else a[i] = '0';
        }
        
        while (carry > 0) {
            if (carry & 1) a = string("1") + a;
            else a = string("0") + a;
            carry >>= 1;
        }
        return a;
    }
};

